package org.jeecg.modules.online.cgform.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.autopoi.poi.excel.ExcelExportUtil;
import org.jeecg.autopoi.poi.excel.ExcelImportUtil;
import org.jeecg.autopoi.poi.excel.entity.ExportParams;
import org.jeecg.autopoi.poi.excel.entity.ImportParams;
import org.jeecg.autopoi.poi.excel.entity.params.ExcelExportEntity;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.OnlineAuth;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.util.BrowserUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.cgform.common.CommonEntity;
import org.jeecg.modules.online.cgform.converter.ConverterUtil;
import org.jeecg.modules.online.cgform.entity.OnlCgformButton;
import org.jeecg.modules.online.cgform.entity.OnlCgformEnhanceJs;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecg.modules.online.cgform.entity.OnlCgformHead;
import org.jeecg.modules.online.cgform.enums.CgformConstant;
import org.jeecg.modules.online.cgform.model.FieldModel;
import org.jeecg.modules.online.cgform.model.OnlCgformHeadModel;
import org.jeecg.modules.online.cgform.model.OnlGenerateModel;
import org.jeecg.modules.online.cgform.model.OnlineConfigModel;
import org.jeecg.modules.online.cgform.model.TreeModel;
import org.jeecg.modules.online.cgform.service.IOnlCgformFieldService;
import org.jeecg.modules.online.cgform.service.IOnlCgformHeadService;
import org.jeecg.modules.online.cgform.service.IOnlCgformSqlService;
import org.jeecg.modules.online.cgform.service.IOnlineService;
import org.jeecg.modules.online.cgform.util.EnhanceJsUtil;
import org.jeecg.modules.online.cgform.util.ExcelDataHandlerDefaultUtil;
import org.jeecg.modules.online.cgform.util.SqlSymbolUtil;
import org.jeecg.modules.online.cgform.util.ZipUtil;
import org.jeecg.modules.online.config.exception.BusinessException;
import org.jeecg.modules.online.config.exception.DBException;
import org.jeecg.modules.online.config.util.TableUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
import org.springframework.jdbc.support.incrementer.PostgresSequenceMaxValueIncrementer;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController("onlCgformApiController")
@RequestMapping({"/online/cgform/api"})
public class OnlCgformApiController {
    @Autowired
    private IOnlCgformHeadService onlCgformHeadService;
    @Autowired
    private IOnlCgformFieldService onlCgformFieldService;
    @Autowired
    private IOnlCgformSqlService onlCgformSqlService;
    @Autowired
    private IOnlineService onlineService;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;
    @Value("${jeecg.uploadType}")
    private String uploadType;

    public OnlCgformApiController() {
    }

    @PostMapping({"/addAll"})
    public Result<?> addAll(@RequestBody OnlCgformHeadModel onlCgformHeadModel) {
        try {
            String tableName = onlCgformHeadModel.getHead().getTableName();
            return TableUtil.isTableExist(tableName) ? Result.error("数据库表[" + tableName + "]已存在,请从数据库导入表单") : this.onlCgformHeadService.addAll(onlCgformHeadModel);
        } catch (Exception e) {
        	log.error("OnlCgformApiController.addAll()发生异常：" + e.getMessage(), e);
            return Result.error("操作失败");
        }
    }

    @PutMapping({"/editAll"})
    public Result<?> editAll(@RequestBody OnlCgformHeadModel onlCgformHeadModel) {
        try {
            return this.onlCgformHeadService.editAll(onlCgformHeadModel);
        } catch (Exception e) {
        	log.error("OnlCgformApiController.editAll()发生异常：" + e.getMessage(), e);
            return Result.error("操作失败");
        }
    }

    @OnlineAuth("getColumns")
    @GetMapping({"/getColumns/{code}"})
    public Result<OnlineConfigModel> getColumns(@PathVariable("code") String code) {
        Result<OnlineConfigModel> result = new Result<>();
        OnlCgformHead onlCgformHead = this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
            result.error500("实体不存在");
            return result;
        } else {
            OnlineConfigModel onlineConfigModel = this.onlineService.queryOnlineConfig(onlCgformHead);
            result.setResult(onlineConfigModel);
            return result;
        }
    }

    @PermissionData
    @OnlineAuth("getData")
    @GetMapping({"/getData/{code}"})
    public Result<Map<String, Object>> getData(@PathVariable("code") String code, HttpServletRequest req) {
        Result<Map<String, Object>> result = new Result<>();
        OnlCgformHead onlCgformHead = this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
            result.error500("实体不存在");
            return result;
        } else {
            try {
                String tableName = onlCgformHead.getTableName();
                Map<String, Object> params = SqlSymbolUtil.getParameterMap(req);
                Map<String, Object>  resultMap = this.onlCgformFieldService.queryAutolistPage(tableName, code, params, null);
                this.recordsEnhance(onlCgformHead, resultMap);
                result.setResult(resultMap);
            } catch (Exception e) {
            	log.error(e.getMessage(), e);
                result.error500("数据库查询失败，" + e.getMessage());
            }

            return result;
        }
    }

    @OnlineAuth("getFormItem")
    @GetMapping({"/getFormItem/{code}"})
    public Result<?> getFormItem(@PathVariable("code") String code, HttpServletRequest request) {
        OnlCgformHead onlCgformHead = this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
            Result.error("表不存在");
        }

        Result<JSONObject> result = new Result<>();
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(code, "form");
        JSONObject jsonObject = this.onlineService.queryOnlineFormObj(onlCgformHead, onlCgformEnhanceJs);
        if (onlCgformHead.getTableType() == CgformConstant.ONLINE_TABLE_TYPE_MAIN) {
            JSONObject jsonObject1 = jsonObject.getJSONObject("schema");
            String subTableStr = onlCgformHead.getSubTableStr();
            if (oConvertUtils.isNotEmpty(subTableStr)) {
                List<OnlCgformHead> arrayList = new ArrayList<OnlCgformHead>();
                String[] subTableStrs = subTableStr.split(",");
                int length = subTableStrs.length;

                for(int i = 0; i < length; ++i) {
                    String subTableStr1 = subTableStrs[i];
                    OnlCgformHead onlCgformHead1 = this.onlCgformHeadService.getOne((new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, subTableStr1));
                    if (onlCgformHead1 != null) {
                    	arrayList.add(onlCgformHead1);
                    }
                }

                if (arrayList.size() > 0) {
                    Collections.sort(arrayList, new Comparator<OnlCgformHead>() {
                    	@Override
                        public int compare(OnlCgformHead onlCgformHead1, OnlCgformHead onlCgformHead2) {
                            Integer orderNum1 = onlCgformHead1.getTabOrderNum();
                            if (orderNum1 == null) {
                            	orderNum1 = 0;
                            }

                            Integer orderNum2 = onlCgformHead2.getTabOrderNum();
                            if (orderNum2 == null) {
                            	orderNum2 = 0;
                            }

                            return orderNum1.compareTo(orderNum2);
                        }
                    });
                    Iterator<OnlCgformHead> iterator = arrayList.iterator();

                    while(iterator.hasNext()) {
                        OnlCgformHead onlCgformHead1 = iterator.next();
                        List<OnlCgformField> availableFields = this.onlCgformFieldService.queryAvailableFields(onlCgformHead1.getId(), onlCgformHead1.getTableName(), (String)null, false);
                        EnhanceJsUtil.getJsFunction(onlCgformEnhanceJs, onlCgformHead1.getTableName(), availableFields);
                        JSONObject jsonObject2 = new JSONObject();
                        List<String> disabledFields = this.onlCgformFieldService.queryDisabledFields(onlCgformHead1.getTableName());
                        if (1 == onlCgformHead1.getRelationType()) {
                        	jsonObject2 = SqlSymbolUtil.getFiledJson(availableFields, disabledFields, (FieldModel)null);
                        } else {
                        	jsonObject2.put("columns", SqlSymbolUtil.getColumns(availableFields, disabledFields));
                        }

                        jsonObject2.put("id", onlCgformHead1.getId());
                        jsonObject2.put("describe", onlCgformHead1.getTableTxt());
                        jsonObject2.put("key", onlCgformHead1.getTableName());
                        jsonObject2.put("view", "tab");
                        jsonObject2.put("order", onlCgformHead1.getTabOrderNum());
                        jsonObject2.put("relationType", onlCgformHead1.getRelationType());
                        jsonObject1.getJSONObject("properties").put(onlCgformHead1.getTableName(), jsonObject2);
                    }
                }
            }

            if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
            	jsonObject.put("enhanceJs", EnhanceJsUtil.getCgJs(onlCgformEnhanceJs.getCgJs()));
            }
        }

        result.setResult(jsonObject);
        return result;
    }

    @GetMapping({"/getFormItemBytbname/{table}"})
    public Result<?> getFormItemBytbname(@PathVariable("table") String table, @RequestParam(name = "taskId",required = false) String taskId) {
        Result<JSONObject> result = new Result<>();
        LambdaQueryWrapper<OnlCgformHead> onlCgformHeadLambdaQueryWrapper = new LambdaQueryWrapper<>();
        onlCgformHeadLambdaQueryWrapper.eq(OnlCgformHead::getTableName, table);
        OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getOne(onlCgformHeadLambdaQueryWrapper);
        if (onlCgformHead == null) {
            Result.error("表不存在");
        }

        JSONObject jsonObject = new JSONObject();
        onlCgformHead.setTaskId(taskId);
        jsonObject.put("schema", this.onlCgformHeadService.queryFormItem(onlCgformHead));
        jsonObject.put("head", onlCgformHead);
        result.setResult(jsonObject);
        return result;
    }

    @OnlineAuth("getEnhanceJs")
    @GetMapping({"/getEnhanceJs/{code}"})
    public Result<?> getEnhanceJs(@PathVariable("code") String code, HttpServletRequest request) {
        String s = "";
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(code, "form");
        if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
            s = EnhanceJsUtil.getJsFunction(onlCgformEnhanceJs.getCgJs(), (List<OnlCgformButton>) null);
        }

        return Result.OK(s);
    }

    @GetMapping({"/form/{code}/{id}"})
    public Result<?> getForm(@PathVariable("code") String code, @PathVariable("id") String id) {
        try {
            Map<String, Object> map = this.onlCgformHeadService.queryManyFormData(code, id);
            return Result.OK(SqlSymbolUtil.getValueType(map));
        } catch (Exception e) {
        	log.error("Online表单查询异常：" + e.getMessage(), e);
            return Result.error("查询失败，" + e.getMessage());
        }
    }

    @GetMapping({"/subform/{table}/{mainId}"})
    public Result<?> subform(@PathVariable("table") String table, @PathVariable("mainId") String mainId) {
        try {
            Map<String, Object> map = this.onlCgformHeadService.querySubFormData(table, mainId);
            return Result.OK(SqlSymbolUtil.getValueType(map));
        } catch (Exception e) {
        	log.error("Online表单查询异常：" + e.getMessage(), e);
            return Result.error("查询失败，" + e.getMessage());
        }
    }

    @GetMapping({"/subform/list/{table}/{mainId}"})
    public Result<?> subformList(@PathVariable("table") String table, @PathVariable("mainId") String mainId) {
        try {
            return Result.OK(this.onlCgformHeadService.queryManySubFormData(table, mainId));
        } catch (Exception e) {
        	log.error("Online表单查询异常：" + e.getMessage(), e);
            return Result.error("查询失败，" + e.getMessage());
        }
    }

    @GetMapping({"/form/table_name/{tableName}/{dataId}"})
    public Result<?> formTableName(@PathVariable("tableName") String tableName, @PathVariable("dataId") String dataId) {
        try {
            LambdaQueryWrapper<OnlCgformHead> onlCgformHeadLambdaQueryWrapper = new LambdaQueryWrapper<>();
            onlCgformHeadLambdaQueryWrapper.eq(OnlCgformHead::getTableName, tableName);
            OnlCgformHead onlCgformHead = this.onlCgformHeadService.getOne(onlCgformHeadLambdaQueryWrapper);
            if (onlCgformHead == null) {
                throw new Exception("OnlCgform tableName: " + tableName + " 不存在！");
            } else {
                return this.getForm(onlCgformHead.getId(), dataId);
            }
        } catch (Exception e) {
        	log.error("Online表单查询异常，" + e.getMessage(), e);
            return Result.error("查询失败，" + e.getMessage());
        }
    }

    @OnlineAuth("form")
    @PostMapping({"/form/{code}"})
    public Result<String> postForm(@PathVariable("code") String code, @RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Result<String> result = new Result<>();

        try {
            String idWorkerId = SqlSymbolUtil.getIdWorkerId();
            jsonObject.put("id", idWorkerId);
            String token = TokenUtils.getTokenByRequest(request);
            this.onlCgformHeadService.saveManyFormData(code, jsonObject, token);
            result.setSuccess(true);
            result.setResult(idWorkerId);
        } catch (Exception e) {
        	log.error("OnlCgformApiController.formAdd()发生异常：", e);
            result.setSuccess(false);
            result.setMessage("保存失败，" + SqlSymbolUtil.getMessage(e));
        }

        return result;
    }

    @OnlineAuth("form")
    @PutMapping({"/form/{code}"})
    public Result<?> putForm(@PathVariable("code") String code, @RequestBody JSONObject jsonObject) {
        try {
            this.onlCgformHeadService.editManyFormData(code, jsonObject);
        } catch (Exception e) {
        	log.error("OnlCgformApiController.formEdit()发生异常：" + e.getMessage(), e);
            return Result.error("修改失败，" + SqlSymbolUtil.getMessage(e));
        }

        return Result.OK("修改成功！",null);
    }

    @OnlineAuth("form")
    @DeleteMapping({"/form/{code}/{id}"})
    public Result<?> deleteForm(@PathVariable("code") String code, @PathVariable("id") String id) {
        try {
            OnlCgformHead onlCgformHead = this.onlCgformHeadService.getById(code);
            if (onlCgformHead == null) {
                return Result.error("实体不存在");
            }

            if ("Y".equals(onlCgformHead.getIsTree())) {
            	id = this.onlCgformFieldService.queryTreeChildIds(onlCgformHead, id);
            }

            if (id.indexOf(",") > 0) {
                if (onlCgformHead.getTableType() == 2) {
                    this.onlCgformFieldService.deleteAutoListMainAndSub(onlCgformHead, id);
                } else {
                    String tableName = onlCgformHead.getTableName();
                    this.onlCgformFieldService.deleteAutoListById(tableName, id);
                }
            } else {
                this.onlCgformHeadService.deleteOneTableInfo(code, id);
            }
        } catch (Exception e) {
        	log.error("OnlCgformApiController.formEdit()发生异常：" + e.getMessage(), e);
            return Result.error("删除失败");
        }

        return Result.OK("删除成功!",null);
    }

    @DeleteMapping({"/formByCode/{code}/{id}"})
    public Result<?> deleteFormByCode(@PathVariable("code") String code, @PathVariable("id") String id) {
        try {
            OnlCgformHead onlCgformHead = this.onlCgformHeadService.getOne((new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, code));
            if (onlCgformHead == null) {
                return Result.error("实体不存在");
            }

            if (id.indexOf(",") > 0) {
                String tableName = onlCgformHead.getTableName();
                this.onlCgformFieldService.deleteAutoListById(tableName, id);
            } else {
                this.onlCgformHeadService.deleteOneTableInfo(onlCgformHead.getId(), id);
            }
        } catch (Exception e) {
        	log.error("OnlCgformApiController.formEdit()发生异常：" + e.getMessage(), e);
            return Result.error("删除失败");
        }

        return Result.OK("删除成功!",null);
    }

    @OnlineAuth("getQueryInfo")
    @GetMapping({"/getQueryInfo/{code}"})
    public Result<?> getQueryInfo(@PathVariable("code") String code) {
        try {
            List<Map<String, String>> autoListQueryInfo = this.onlCgformFieldService.getAutoListQueryInfo(code);
            return Result.OK(autoListQueryInfo);
        } catch (Exception e) {
        	log.error("OnlCgformApiController.getQueryInfo()发生异常：" + e.getMessage(), e);
            return Result.error("查询失败");
        }
    }

    @PostMapping({"/doDbSynch/{code}/{synMethod}"})
    public Result<?> doDbSynch(@PathVariable("code") String code, @PathVariable("synMethod") String synMethod) {
        try {
            long currentTimeMillis = System.currentTimeMillis();
            this.onlCgformHeadService.doDbSynch(code, synMethod);
            log.info("==同步数据库消耗时间" + (System.currentTimeMillis() - currentTimeMillis) + "毫秒");
        } catch (Exception e) {
        	log.error(e.getMessage(), e);
            return Result.error("同步数据库失败，" + SqlSymbolUtil.getMessage(e));
        }

        return Result.OK("同步数据库成功!",null);
    }

    @OnlineAuth("exportXls")
    @PermissionData
    @GetMapping({"/exportXls/{code}"})
    public void exportXls(@PathVariable("code") String code, HttpServletRequest request, HttpServletResponse response) {
        OnlCgformHead onlCgformHead = this.onlCgformHeadService.getById(code);
        if (onlCgformHead != null) {
            String tableTxt = onlCgformHead.getTableTxt();
            String paramsStr = request.getParameter("paramsStr");
            Map<String,Object> hashMap = new HashMap<>();
            String params = null;
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                try {
                	params = URLDecoder.decode(paramsStr, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                	log.error(e.getMessage(), e);
                }

                if (params != null) {
                	hashMap = JSONObject.parseObject(params, Map.class);
                }
            }

            hashMap.put("pageSize", -521);
            Map<String, Object> autolistPage = this.onlCgformFieldService.queryAutolistPage(onlCgformHead.getTableName(), onlCgformHead.getId(), hashMap, null);
            List<OnlCgformField> fieldList = (List<OnlCgformField>) autolistPage.get("fieldList");
            List<Map<String, Object>> records = (List<Map<String, Object>>) autolistPage.get("records");
            List<Map<String, Object>> var12 = new ArrayList<>();
            String var13 = hashMap.get("selections") == null ? null : hashMap.get("selections").toString();
            List var14;
            if (oConvertUtils.isNotEmpty(var13)) {
                var14 = Arrays.asList(var13.split(","));
                List finalVar1 = var14;
                var12 = records.stream().filter((record) -> {
                    return finalVar1.contains(record.get("id"));
                }).collect(Collectors.toList());
            } else {
                if (records == null) {
                	records = new ArrayList<Map<String, Object>>();
                }

                var12.addAll(records);
            }

            ConverterUtil.converter(1, var12, fieldList);

            try {
                this.onlCgformHeadService.executeEnhanceExport(onlCgformHead, var12);
            } catch (BusinessException e) {
            	log.error("导出java增强处理出错", e.getMessage());
            }

            var14 = this.getExcelEntities(fieldList, "id");
            if (onlCgformHead.getTableType() == 2 && oConvertUtils.isEmpty(hashMap.get("exportSingleOnly"))) {
                String var15 = onlCgformHead.getSubTableStr();
                if (oConvertUtils.isNotEmpty(var15)) {
                    String[] var16 = var15.split(",");
                    String[] var17 = var16;
                    int var18 = var16.length;

                    for(int i = 0; i < var18; ++i) {
                        String var20 = var17[i];
                        this.getSubTableDataForExcel(var20, hashMap, var12, var14);
                    }
                }
            }

            Workbook var35 = ExcelExportUtil.exportExcel(new ExportParams((String)null, tableTxt), var14, (Collection)var12);
            ServletOutputStream var36 = null;

            try {
            	response.setContentType("application/x-msdownload;charset=utf-8");
                String var37 = BrowserUtils.checkBrowse(request);
                String var38 = onlCgformHead.getTableTxt() + "-v" + onlCgformHead.getTableVersion();
                if ("MSIE".equalsIgnoreCase(var37.substring(0, 4))) {
                	response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(var38, "UTF-8") + ".xls");
                } else {
                    String var39 = new String(var38.getBytes("UTF-8"), "ISO8859-1");
                    response.setHeader("content-disposition", "attachment;filename=" + var39 + ".xls");
                }

                var36 = response.getOutputStream();
                var35.write(var36);
                response.flushBuffer();
            } catch (Exception var31) {
            	log.error("--通过流的方式获取文件异常--" + var31.getMessage(), var31);
            } finally {
                if (var36 != null) {
                    try {
                        var36.close();
                    } catch (IOException var30) {
                    	log.error(var30.getMessage(), var30);
                    }
                }

            }

        }
    }

    @OnlineAuth("importXls")
    @PostMapping({"/importXls/{code}"})
    public Result<?> importXls(@PathVariable("code") String code, HttpServletRequest request, HttpServletResponse response) {
        long start = System.currentTimeMillis();
        Result<?> result = new Result<>();
        String msg = "";

        try {
            OnlCgformHead head = this.onlCgformHeadService.getById(code);
            if (head == null) {
                return Result.error("数据库不存在该表记录");
            }

            LambdaQueryWrapper<OnlCgformField> qw = new LambdaQueryWrapper<>();
            qw.eq(OnlCgformField::getCgformHeadId, code);
            List<OnlCgformField> fields = this.onlCgformFieldService.list(qw);
            String isSingleTableImport = request.getParameter("isSingleTableImport");
            List<String> imageList = SqlSymbolUtil.getImageList(fields);
            if (oConvertUtils.isEmpty(isSingleTableImport) && head.getTableType() == 2 && oConvertUtils.isNotEmpty(head.getSubTableStr())) {
                String[] subTableStr = head.getSubTableStr().split(",");

                for(int i = 0; i < subTableStr.length; ++i) {
                    String subTableName = subTableStr[i];
                    OnlCgformHead subTableHead = this.onlCgformHeadService.getOne((new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, subTableName));
                    if (subTableHead != null) {
                        List<OnlCgformField> subFields = this.onlCgformFieldService.list((new LambdaQueryWrapper<OnlCgformField>()).eq(OnlCgformField::getCgformHeadId, subTableHead.getId()));
                        List<String> subImageList = SqlSymbolUtil.getSubImageList(subFields, subTableHead.getTableTxt());
                        if (subImageList.size() > 0) {
                        	imageList.addAll(subImageList);
                        }
                    }
                }
            }

            JSONObject foreignKeysJson = null;
            String foreignKeys = request.getParameter("foreignKeys");
            if (oConvertUtils.isNotEmpty(foreignKeys)) {
            	foreignKeysJson = JSONObject.parseObject(foreignKeys);
            }

            MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = fileRequest.getFileMap();
            DataSource ds = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
            String dbType = TableUtil.getDatabaseType(ds);
            Iterator<Entry<String, MultipartFile>> iterator = fileMap.entrySet().iterator();

            while(iterator.hasNext()) {
                Entry<String, MultipartFile> fileMapEntry = iterator.next();
                MultipartFile file = fileMapEntry.getValue();
                ImportParams params = new ImportParams();
                params.setImageList(imageList);
                params.setDataHanlder(new ExcelDataHandlerDefaultUtil(fields, this.upLoadPath, this.uploadType));
                List<Object> records = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);
                if (records != null) {
                    Object var24 = "";
                    ArrayList var25 = new ArrayList();

                    Map var27;
                    for(Iterator<Object> var26 = records.iterator(); var26.hasNext(); var27.put("$mainTable$id", var24)) {
                        var27 = (Map)var26.next();
                        boolean var28 = false;
                        Set var29 = var27.keySet();
                        HashMap var30 = new HashMap();
                        Iterator var31 = var29.iterator();

                        String var32;
                        while(var31.hasNext()) {
                            var32 = (String)var31.next();
                            if (var32.indexOf("$subTable$") == -1) {
                                if (var32.indexOf("$mainTable$") != -1 && oConvertUtils.isNotEmpty(var27.get(var32).toString())) {
                                    var28 = true;
                                    var24 = this.getNextIdValue(head, ds, dbType);
                                }

                                var30.put(var32.replace("$mainTable$", ""), var27.get(var32));
                            }
                        }

                        if (var28) {
                            var30.put("id", var24);
                            var25.add(var30);
                            var24 = var30.get("id");
                        }

                        if (foreignKeysJson != null) {
                            var31 = foreignKeysJson.keySet().iterator();

                            while(var31.hasNext()) {
                                var32 = (String)var31.next();
                                System.out.println(var32 + "=" + foreignKeysJson.getString(var32));
                                var30.put(var32, foreignKeysJson.getString(var32));
                            }
                        }
                    }

                    if (var25 == null || var25.size() == 0) {
                    	result.setSuccess(false);
                        result.setMessage("导入失败，匹配的数据条数为零!");
                        return result;
                    }

                    this.onlCgformSqlService.saveBatchOnlineTable(head, fields, var25);
                    if (oConvertUtils.isEmpty(isSingleTableImport) && head.getTableType() == 2 && oConvertUtils.isNotEmpty(head.getSubTableStr())) {
                        String[] var54 = head.getSubTableStr().split(",");
                        int var55 = var54.length;

                        for(int var56 = 0; var56 < var55; ++var56) {
                            String var57 = var54[var56];
                            OnlCgformHead var58 = (OnlCgformHead)this.onlCgformHeadService.getOne((Wrapper)(new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, var57));
                            if (var58 != null) {
                                LambdaQueryWrapper<OnlCgformField> var59 = new LambdaQueryWrapper();
                                var59.eq(OnlCgformField::getCgformHeadId, var58.getId());
                                List var60 = this.onlCgformFieldService.list(var59);
                                ArrayList var33 = new ArrayList();
                                String var34 = var58.getTableTxt();
                                Iterator var35 = records.iterator();

                                while(var35.hasNext()) {
                                    Map var36 = (Map)var35.next();
                                    boolean var37 = false;
                                    HashMap var38 = new HashMap();
                                    Iterator var39 = var60.iterator();

                                    while(var39.hasNext()) {
                                        OnlCgformField var40 = (OnlCgformField)var39.next();
                                        String var41 = var40.getMainTable();
                                        String var42 = var40.getMainField();
                                        boolean var43 = head.getTableName().equals(var41) && oConvertUtils.isNotEmpty(var42);
                                        String var44 = var34 + "_" + var40.getDbFieldTxt();
                                        if (var43) {
                                            var38.put(var40.getDbFieldName(), var36.get("$mainTable$" + var42));
                                        }

                                        Object var45 = var36.get("$subTable$" + var44);
                                        if (null != var45 && oConvertUtils.isNotEmpty(var45.toString())) {
                                            var37 = true;
                                            var38.put(var40.getDbFieldName(), var45);
                                        }
                                    }

                                    if (var37) {
                                        var38.put("id", this.getNextIdValue(var58, ds, dbType));
                                        var33.add(var38);
                                    }
                                }

                                if (var33.size() > 0) {
                                    this.onlCgformSqlService.saveBatchOnlineTable(var58, var60, var33);
                                }
                            }
                        }
                    }

                    msg = "文件导入成功！";
                } else {
                	msg = "识别模版数据错误";
                    log.error(msg);
                }
            }

                result.setSuccess(true);
                result.setMessage("导入成功!");
        } catch (Exception e) {
        	result.setSuccess(false);
        	result.setMessage(e.getMessage());
            log.error(e.getMessage(), e);
        }

        log.info("=====online导入数据完成,耗时:" + (System.currentTimeMillis() - start) + "毫秒=====");
        return result;
    }

    @PostMapping({"/doButton"})
    public Result<?> doButton(@RequestBody JSONObject json) {
        String formId = json.getString("formId");
        String dataId = json.getString("dataId");
        String buttonCode = json.getString("buttonCode");
        // JSONObject uiFormData = json.getJSONObject("uiFormData");

        try {
            this.onlCgformHeadService.executeCustomerButton(buttonCode, formId, dataId);
        } catch (Exception e) {
        	log.error(e.getMessage(), e);
            return Result.error("执行失败!");
        }

        return Result.OK("执行成功!",null);
    }

    public Object getNextIdValue(OnlCgformHead head, DataSource ds, String dbType) throws SQLException, DBException {
        Object id = null;
        String idType = head.getIdType();
        String idSequence = head.getIdSequence();
        if (oConvertUtils.isNotEmpty(idType) && "UUID".equalsIgnoreCase(idType)) {
        	id = SqlSymbolUtil.getIdWorkerId();
        } else {
        	PostgresSequenceMaxValueIncrementer postgresSequence;
            OracleSequenceMaxValueIncrementer oracleSequence;
            if (oConvertUtils.isNotEmpty(idType) && "NATIVE".equalsIgnoreCase(idType)) {
                if (oConvertUtils.isNotEmpty(dbType) && "oracle".equalsIgnoreCase(dbType)) {
                	oracleSequence = new OracleSequenceMaxValueIncrementer(ds, "HIBERNATE_SEQUENCE");

                    try {
                    	id = oracleSequence.nextLongValue();
                    } catch (Exception e) {
                    	log.error(e.getMessage(), e);
                    }
                } else if (oConvertUtils.isNotEmpty(dbType) && "postgres".equalsIgnoreCase(dbType)) {
                	postgresSequence = new PostgresSequenceMaxValueIncrementer(ds, "HIBERNATE_SEQUENCE");

                    try {
                    	id = postgresSequence.nextLongValue();
                    } catch (Exception e) {
                    	log.error(e.getMessage(), e);
                    }
                } else {
                	id = null;
                }
            } else if (oConvertUtils.isNotEmpty(idType) && "SEQUENCE".equalsIgnoreCase(idType)) {
                if (oConvertUtils.isNotEmpty(dbType) && "oracle".equalsIgnoreCase(dbType)) {
                	oracleSequence = new OracleSequenceMaxValueIncrementer(ds, idSequence);

                    try {
                    	id = oracleSequence.nextLongValue();
                    } catch (Exception e) {
                    	log.error(e.getMessage(), e);
                    }
                } else if (oConvertUtils.isNotEmpty(dbType) && "postgres".equalsIgnoreCase(dbType)) {
                	postgresSequence = new PostgresSequenceMaxValueIncrementer(ds, idSequence);

                    try {
                    	id = postgresSequence.nextLongValue();
                    } catch (Exception e) {
                    	log.error(e.getMessage(), e);
                    }
                } else {
                	id = null;
                }
            } else {
            	id = SqlSymbolUtil.getIdWorkerId();
            }
        }

        return id;
    }

    /*private void a(Map var1, List<OnlCgformField> fields) {
        Iterator<OnlCgformField> var3 = fields.iterator();

        while(true) {
            OnlCgformField var4;
            String var5;
            String var6;
            String var7;
            do {
                do {
                    if (!var3.hasNext()) {
                        return;
                    }

                    var4 = (OnlCgformField)var3.next();
                    var5 = var4.getDictTable();
                    var6 = var4.getDictField();
                    var7 = var4.getDictText();
                } while(oConvertUtils.isEmpty(var5) && oConvertUtils.isEmpty(var6));
            } while("popup".equals(var4.getFieldShowType()));

            String var9 = String.valueOf(var1.get(var4.getDbFieldName()));
            List var8;
            if (oConvertUtils.isEmpty(var5)) {
                var8 = this.sysBaseAPI.queryDictItemsByCode(var6);
            } else {
                var8 = this.sysBaseAPI.queryTableDictItemsByCode(var5, var7, var6);
            }

            Iterator var10 = var8.iterator();

            while(var10.hasNext()) {
                DictModel var11 = (DictModel)var10.next();
                if (var9.equals(var11.getText())) {
                    var1.put(var4.getDbFieldName(), var11.getValue());
                }
            }
        }
    }*/

    private List<ExcelExportEntity> getExcelEntities(List<OnlCgformField> fields, String idField) {
        List<ExcelExportEntity> entities = new ArrayList<>();

        for(int i = 0; i < fields.size(); ++i) {
            if ((null == idField || !idField.equals((fields.get(i)).getDbFieldName())) && (fields.get(i)).getIsShowList() == 1) {
                String dbFieldName = (fields.get(i)).getDbFieldName();
                ExcelExportEntity entity = new ExcelExportEntity((fields.get(i)).getDbFieldTxt(), dbFieldName);
                if ("image".equals((fields.get(i)).getFieldShowType())) {
                	entity.setType(2);
                	entity.setExportImageType(3);
                	entity.setImageBasePath(this.upLoadPath);
                	entity.setHeight(50.0D);
                	entity.setWidth(60.0D);
                } else {
                    int width = (fields.get(i)).getDbLength() == 0 ? 12 : ((fields.get(i)).getDbLength() > 30 ? 30 : (fields.get(i)).getDbLength());
                    if ((fields.get(i)).getFieldShowType().equals("date")) {
                    	entity.setFormat("yyyy-MM-dd");
                    } else if ((fields.get(i)).getFieldShowType().equals("datetime")) {
                    	entity.setFormat("yyyy-MM-dd HH:mm:ss");
                    }

                    if (width < 10) {
                    	width = 10;
                    }

                    entity.setWidth((double)width);
                }

                entities.add(entity);
            }
        }

        return entities;
    }

    private void getSubTableDataForExcel(String tbname, Map<String, Object> var2, List<Map<String, Object>> var3, List<ExcelExportEntity> var4) {
        OnlCgformHead head = this.onlCgformHeadService.getOne((new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, tbname));
        LambdaQueryWrapper<OnlCgformField> qw = new LambdaQueryWrapper<OnlCgformField>();
        qw.eq(OnlCgformField::getCgformHeadId, head.getId());
        qw.orderByAsc(OnlCgformField::getOrderNum);
        List<OnlCgformField> fields = this.onlCgformFieldService.list(qw);
        String mainField = "";
        String dbFieldName = "";
        Iterator<OnlCgformField> var10 = fields.iterator();

        while(var10.hasNext()) {
            OnlCgformField var11 = var10.next();
            if (oConvertUtils.isNotEmpty(var11.getMainField())) {
            	mainField = var11.getMainField();
            	dbFieldName = var11.getDbFieldName();
                break;
            }
        }

        ExcelExportEntity entity = new ExcelExportEntity(head.getTableTxt(), tbname);
        entity.setList(this.getExcelEntities(fields, "id"));
        var4.add(entity);

        for(int i = 0; i < var3.size(); ++i) {
            var2.put(dbFieldName, ((Map)var3.get(i)).get(mainField));
            String var12 = SqlSymbolUtil.a(head.getTableName(), fields, var2);
            log.info("-----------动态列表查询子表sql》》" + var12);
            List var13 = this.onlCgformHeadService.queryListData(var12);
            ConverterUtil.converter(1, var13, fields);
            ((Map)var3.get(i)).put(tbname, SqlSymbolUtil.transforRecords(var13));
        }

    }

    @GetMapping({"/checkOnlyTable"})
    public Result<?> checkOnlyTable(@RequestParam("tbname") String tableName, @RequestParam("id") String id) {
        OnlCgformHead head;
        if (oConvertUtils.isEmpty(id)) {
            if (TableUtil.isTableExist(tableName)) {
                return Result.OK(-1);
            }

            head = this.onlCgformHeadService.getOne((new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, tableName));
            if (oConvertUtils.isNotEmpty(head)) {
                return Result.OK(-1);
            }
        } else {
        	head = (OnlCgformHead)this.onlCgformHeadService.getById(id);
            if (!tableName.equals(head.getTableName()) && TableUtil.isTableExist(tableName)) {
                return Result.OK(-1);
            }
        }

        return Result.OK(1);
    }

    @PostMapping({"/codeGenerate"})
    public Result<?> codeGenerate(@RequestBody JSONObject json) {
        OnlGenerateModel model = JSONObject.parseObject(json.toJSONString(), OnlGenerateModel.class);
        List<String> codeList = null;

        try {
            if ("1".equals(model.getJformType())) {
            	codeList = this.onlCgformHeadService.generateCode(model);
            } else {
            	codeList = this.onlCgformHeadService.generateOneToMany(model);
            }

            return Result.OK(codeList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @GetMapping({"/downGenerateCode"})
    public void downGenerateCode(@RequestParam("fileList") List<String> fileList, HttpServletRequest req, HttpServletResponse resp) {
        List var4 = fileList.stream().filter((file) -> {
            return file.indexOf("src/main/java") == -1 && file.indexOf("src%5Cmain%5Cjava") == -1;
        }).collect(Collectors.toList());
        if (fileList != null && (var4 == null || var4.size() <= 0)) {
            String zipName = "生成代码_" + System.currentTimeMillis() + ".zip";
            String zipPath = "/opt/temp/codegenerate/" + zipName;
            File var7 = ZipUtil.compressFiles(fileList, zipPath);
            if (var7.exists()) {
            	resp.setContentType("application/force-download");
            	resp.addHeader("Content-Disposition", "attachment;fileName=" + zipName);
                byte[] var8 = new byte[1024];
                FileInputStream var9 = null;
                BufferedInputStream var10 = null;

                try {
                    var9 = new FileInputStream(var7);
                    var10 = new BufferedInputStream(var9);
                    ServletOutputStream var11 = resp.getOutputStream();

                    for(int var12 = var10.read(var8); var12 != -1; var12 = var10.read(var8)) {
                        var11.write(var8, 0, var12);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (var10 != null) {
                        try {
                            var10.close();
                        } catch (IOException var24) {
                            var24.printStackTrace();
                        }
                    }

                    if (var9 != null) {
                        try {
                            var9.close();
                        } catch (IOException var23) {
                            var23.printStackTrace();
                        }
                    }

                    class DelFile extends Thread {
                        public void run() {
                            try {
                                Thread.sleep(10000L);
                                FileUtil.del(zipPath);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                    (new DelFile()).start();
                }
            }

        } else {
        	log.error(" fileList 不合法！！！", fileList);
        }
    }

    @GetMapping({"/getTreeData/{code}"})
    @PermissionData
    public Result<Map<String, Object>> getTreeData(@PathVariable("code") String code, HttpServletRequest request) {
        Result<Map<String, Object>> result = new Result<>();
        OnlCgformHead head = this.onlCgformHeadService.getById(code);
        if (head == null) {
        	result.error500("实体不存在");
            return result;
        } else {
            try {
                String tableName = head.getTableName();
                String treeIdField = head.getTreeIdField();
                String treeParentIdField = head.getTreeParentIdField();
                List<String> needList = Lists.newArrayList(new String[]{treeIdField, treeParentIdField});
                Map<String, Object> params = SqlSymbolUtil.getParameterMap(request);
                String var10 = null;
                if (params.get(treeIdField) != null) {
                    var10 = params.get(treeIdField).toString();
                }

                if (params.get("hasQuery") != null && "false".equals(params.get("hasQuery")) && params.get(treeParentIdField) == null) {
                	params.put(treeParentIdField, "0");
                } else {
                	params.put("pageSize", -521);
                	params.put(treeParentIdField, params.get(treeParentIdField));
                }

                params.put(treeIdField, (Object)null);
                Map<String, Object> treeMap = this.onlCgformFieldService.queryAutoTreeNoPage(tableName, code, params, needList, treeParentIdField);
                this.recordsEnhance(head, treeMap);
                result.setResult(treeMap);
            } catch (Exception e) {
            	log.error(e.getMessage(), e);
            	result.error500("数据库查询失败" + e.getMessage());
            }

            return result;
        }
    }

    private void recordsEnhance(OnlCgformHead onlCgformHead, Map<String, Object> resultMap) throws BusinessException {
        List<Map<String,Object>> records = (List<Map<String,Object>>) resultMap.get("records");
        this.onlCgformHeadService.executeEnhanceList(onlCgformHead, "query", records);
    }

    @PostMapping({"/crazyForm/{name}"})
    public Result<String> formAddForDesigner(@PathVariable("name") String name, @RequestBody JSONObject json) {
        Result<String> result = new Result<>();

        try {
            String id = SqlSymbolUtil.getIdWorkerId();
            json.put("id", id);
            this.onlCgformHeadService.addCrazyFormData(name, json);
            result.setResult(id);
            result.setMessage("保存成功");
            return result;
        } catch (Exception e) {
        	log.error("OnlCgformApiController.formAddForDesigner()发生异常：" + e.getMessage(), e);
        	result.error500("保存失败");
            return result;
        }
    }

    @PutMapping({"/crazyForm/{name}"})
    public Result<?> formEditForDesigner(@PathVariable("name") String name, @RequestBody JSONObject json) {
        try {
            this.onlCgformHeadService.editCrazyFormData(name, json);
        } catch (Exception e) {
        	log.error("OnlCgformApiController.formEditForDesigner()发生异常：" + e.getMessage(), e);
            return Result.error("保存失败");
        }

        return Result.OK("保存成功!",null);
    }

    @GetMapping({"/getErpColumns/{code}"})
    public Result<Map<String, Object>> getErpColumns(@PathVariable("code") String code) {
        Result<Map<String, Object>> result = new Result<>();
        OnlCgformHead onlCgformHead = this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
        	result.error500("实体不存在");
            return result;
        } else {
            Map<String, Object> map = new HashMap<>();
            OnlineConfigModel onlineConfigModel = this.onlineService.queryOnlineConfig(onlCgformHead);
            map.put("main", onlineConfigModel);
            if ("erp".equals(onlCgformHead.getThemeTemplate()) && onlCgformHead.getTableType() == 2) {
                String subTableStr = onlCgformHead.getSubTableStr();
                if (oConvertUtils.isNotEmpty(subTableStr)) {
                    List<OnlineConfigModel> subList = new ArrayList<>();
                    String[] subTableStrArr = subTableStr.split(",");

                    for(int i = 0; i < subTableStrArr.length; ++i) {
                        String subTableName = subTableStrArr[i];
                        OnlCgformHead subTableHead = this.onlCgformHeadService.getOne((new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, subTableName));
                        if (subTableHead != null) {
                        	subList.add(this.onlineService.queryOnlineConfig(subTableHead));
                        }
                    }

                    if (subList.size() > 0) {
                    	map.put("subList", subList);
                    }
                }
            }

            result.setResult(map);
            result.setSuccess(true);
            return result;
        }
    }

    @GetMapping({"/getErpFormItem/{code}"})
    public Result<JSONObject> getErpFormItem(@PathVariable("code") String code, HttpServletRequest request) {
        OnlCgformHead head = this.onlCgformHeadService.getById(code);
        if (head == null) {
            Result.error("表不存在");
        }

        Result<JSONObject> result = new Result<>();
        JSONObject onlineFormObj = this.onlineService.queryOnlineFormObj(head);
        result.setResult(onlineFormObj);
        return result;
    }

    @GetMapping({"/querySelectOptions"})
    public Result<List<TreeModel>> querySelectOptions(@ModelAttribute CommonEntity entity) {
        Result<List<TreeModel>> result = new Result<>();
        List<TreeModel> treeModels = this.onlCgformFieldService.queryDataListByLinkDown(entity);
        result.setResult(treeModels);
        result.setSuccess(true);
        return result;
    }

    /**
     * 根据子表表名查询子表code
     * @param tableName
     * @return
     */
    @GetMapping({"/getSubTableCode/{tableName}"})
    public Result<List<OnlCgformHead>> getSubTableCode(@PathVariable("tableName") String tableName) {
        Result<List<OnlCgformHead>> result = new Result<>();
        List<OnlCgformHead> onlCgformHeads = new ArrayList<>();

        String[] tableNames = tableName.split(",");
        for (String tn : tableNames) {
            OnlCgformHead onlCgformHead = this.onlCgformHeadService.getOne(new QueryWrapper<OnlCgformHead>()
                    .eq("table_name", tn));
            if (onlCgformHead != null) {
                onlCgformHeads.add(onlCgformHead);
            }
        }

        result.setResult(onlCgformHeads);
        return result;
    }
}
